import axios from "../../../utils/axios";
import dayjs from 'dayjs';
import {findPriceByDuration} from "../../../utils/util"
const formatTime = 'YYYY-MM-DD HH:mm';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    item: {},
    orderDetail: {},
    timePeriod: '',
    duration: 0,
    amount: 0, // 费用小计
    balance: "0.00", // 会员余额
    price: 0, // 应付金额
    yezf: [{
      value: "v",
      checked: true
    }],
    isYezf: false, //会员余额支付复选框
    marks: {
      0: 0,
      100: 0,
    },
    step: 1,
    loading: false,
    stepDuration: 0
  },
  getYfje(isYezf){
    const {
      price,
      balance
    } = this.data;
    let amount = 0;

    if (isYezf) {
      // 使用余额支付
      if (balance >= price) {
        amount = 0
      } else {
        amount -= balance;
      }
      amount = amount.toFixed(2);
    } else {
      amount = price.toFixed(2)
    }
    return amount;
  },
  checkboxChange: function (e) {
    // 当复选框的选中状态发生变化时，会触发checkboxChange事件  
    // e.detail.value数组中包含了所有选中项的value值  
    const isYezf = e.detail.value.length === 1;
    const amount = this.getYfje(isYezf);
    this.setData({
      isYezf,
      amount
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.openid = wx.getStorageSync('openid');
    this.setData({
      roomId: options.roomId * 1,
      orderId: options.orderId * 1
    })
    this.queryBalance();
  },
  onShow() {

  },
  getRoomDetail() {
    axios.get("/app/roomList", {
      company_id: this.data.orderDetail.companyId
    }).then(res => {
      const room = res.data.find(item => item.ID === this.data.roomId)
      this.setData({
        item: room
      })
      this.getDuration();
    })
  },
  queryBalance() {
    axios.get("/app/memberList", {
      wxId: wx.getStorageSync('openid')
    }).then(res => {
      this.getOrderDetail(this.data.item);
      const balance = res.data[0].balance.toFixed(2);
      const isYezf = balance > 0;
      this.setData({
        balance,
        isYezf
      })
    })
  },
  async getOrderDetail() {
    const {
      orderId,
    } = this.data;
    if(!orderId){
      return;
    }
    const res = await axios.get(`/app/orderList?wxId=${this.openid}&ID=${orderId}`);
    let orderDetail = res?.data?.[0];
    const timePeriod = `${dayjs(orderDetail.startTime).format(formatTime)} - ${dayjs(orderDetail.endTime).format(
      'HH:mm',
    )}`;
    const duration = dayjs(orderDetail.endTime).diff(dayjs(orderDetail.startTime), 'hour');
    let price = 0;
    let amount = price;
    const balance = this.data.balance;
    if (balance >= price) {
      amount = 0
    } else {
      amount -= balance;
    }
    amount = amount.toFixed(2);
    this.setData({
      orderDetail,
      timePeriod,
      duration,
      amount
    });
    this.getRoomDetail();
  },
  async getDuration() {
    return axios.get("/app/getDuration",{
      orderId:this.data.orderId,
      roomId:this.data.roomId
    }).then(res => {
      const marks = generatePercentageObject(res.data);
      if (Object.keys(marks).length === 0) {
        wx.showToast({
          title: '暂时不可续费',
          duration: 3000,
          icon: "error"
        })
        return;
      }
      const step = Object.keys(marks).sort((a, b) => a - b)[0];
      this.setPrice(marks[step]);
      this.setData({
        marks,
        step: step * 1,
        stepDuration: step
      })
      return res.data;
    })
  },
  setPrice(dur =0) {
    // 根据时长设置价格
    const {
      item
    } = this.data;
    let price = findPriceByDuration(item.price_list,dur/60)*(dur/60);
    this.setData({
      price:price.toFixed(2)*1
    })
  },
  handleChange(e) {
    this.setData({
      stepDuration: e.detail.value,
    })
    let dr = this.data.marks[e.detail.value]
    this.setPrice(dr)
    const amount = this.getYfje(this.data.isYezf);
    this.setData({
      amount
    })
  },
  wxPay(amounts) {
    const {
      name
    } = this.data.item;
    const {
      stepDuration,
      marks,
      orderId
    } = this.data;
    axios.post('/app/toPay', {
        openid: this.openid,
        orderId,
        name: `${name} 续费 ${marks[stepDuration]}分钟`,
        payment: amounts.price.toFixed(2) * 1,
        balance: amounts.balance * 1,
        duration:marks[stepDuration]*1
      })
      .then((res) => {
        if (res.data === "success") {
          this.payCallback()
          return;
        }
        const {
          nonceStr,
          timeStamp,
          signType,
          paySign
        } = res.data;
        const that = this;
        wx.requestPayment({
          timeStamp,
          nonceStr,
          package: res.data.package,
          signType,
          paySign,
          success() {
            that.payCallback()
          },
          fail() {
            wx.showToast({
              title: '支付取消',
              icon: 'error'
            })
          },
        });
      });
  },
  pay() {
    // price：原价
    // balance: 会员余额
    // amount：应付金额
    const {
      price,
      isYezf,
      balance,
      amount,
      marks,
      stepDuration
    } = this.data;
    if(marks[stepDuration] < 30 || marks[stepDuration] === undefined){
      wx.showToast({
        title: '续费时长小于半小时',
        duration: 3000,
        icon: "none"
      })
      return;
    }
    if (isYezf) {
      if (balance >= price) {
        //余额支付 ，余额足够支付
        this.wxPay({
          price: 0,
          balance: price
        });
      } else {
        // 有余额，但是不够订单金额，扣余额并支付
        this.wxPay({
          price: amount,
          balance
        });
      }
    } else {
      // 不使用会员余额
      this.wxPay({
        price,
        balance: 0
      });
    }
  },
  payCallback() {
    wx.showToast({
      title: '支付成功',
      icon: 'none'
    })
    setTimeout(()=>{
      wx.switchTab({
        url: '/pages/due/due',
      })
    },1500)
    
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});

function generatePercentageObject(maxValue) {
  const result = {};
  const step = (100 / (maxValue / 30)).toString().slice(0,5);
  let count = 1;
  while(step * count <= 100){
    result[(step*count).toFixed(2)*1] = count * 30;
    count++;
  }
  return result;
}
